//
//  SendViewController.swift
//  NewWeiBo
//
//  Created by 吴天益 on 2017/7/31.
//  Copyright © 2017年 ttt. All rights reserved.
//

import UIKit
import SnapKit

class SendViewController: UIViewController,UITextViewDelegate {
    
    
    //懒加载textView
    private lazy var textView: HMTextView = {
    
        let tv = HMTextView()
        
        tv.font = UIFont.systemFont(ofSize: 16)
        tv.placeHolder = "请输入微博信息"
        
        tv.alwaysBounceVertical = true
        
        return tv
    }()
    
    //懒加载图片选择view
    fileprivate lazy var picChooseView: PictureChooseView = PictureChooseView()
    
    //懒加载toolBar
    private lazy var toolBar: SendToolBar = SendToolBar()
    
    //懒加载表情选择视图
    lazy var faceChoose: FaceChooseView = {
        //216是不带提示栏的键盘高度
        let view = FaceChooseView.init(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: ScreenWidth, height: 216)))
    
        return view
    }()
    


    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //输入表情通知注册
        NotificationCenter.default.addObserver(self, selector: #selector(addFaceToTextView(noti:)), name: NSNotification.Name(AddFaceToTextView), object: nil)
        //删除按钮的通知注册
        NotificationCenter.default.addObserver(self, selector: #selector(deleteContentOfTextView(noti:)), name: NSNotification.Name(DeleteContentOfTextView), object: nil)
        
        //注册keyboard监听方法,监听键盘frame的改变
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardChange(noti:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
        
        self.automaticallyAdjustsScrollViewInsets = false

        setupNavi()
        setupUI()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //MARK: - 删除按钮的通知方法的实现
    func deleteContentOfTextView(noti: NSNotification){
        //回删内容
        textView.deleteBackward()
        
        if textView.text == ""{
            textView.placeHolder = "请输入文字"
        }
    }
    
    //MARK: - 输入表情通知方法实现
    func addFaceToTextView(noti: Notification){
        
        textView.placeHolder = ""
        
        let faceModel: FaceModel = noti.object as! FaceModel
        
        if faceModel.type == "0" {
            
            let textAttachment = NSTextAttachment()
            
            //设置图片为复文本
            textAttachment.image = UIImage(named: faceModel.path!, in: FaceViewModel.shareModel.bundle, compatibleWith: nil)
            
            //获取文本行高
            let lineHeight = textView.font?.lineHeight
            
            //设置复文本的bounds,设置bounds会影响子控件的位置
            textAttachment.bounds = CGRect(x: 0, y: -4, width: lineHeight!, height: lineHeight!)
            
            //复文本
            let attrbuteStr = NSAttributedString(attachment: textAttachment)
            
            //获取当前textView的内容
            let nowAttrStr = NSMutableAttributedString(attributedString: textView.attributedText)
            
            //获取光标选中范围
            var selectRange = textView.selectedRange
            //将光标选中范围替换成复文本
            nowAttrStr.replaceCharacters(in: selectRange, with: attrbuteStr)
            
            //统一设置字体
            nowAttrStr.addAttribute(NSFontAttributeName, value: textView.font!, range: NSMakeRange(0, nowAttrStr.length))
  
            //赋值新的复文本
            textView.attributedText = nowAttrStr
            
            
            //不让光标变到最后,让光标停留在添加表情的后面
            selectRange.location += 1
            //设置长度为0
            selectRange.length = 0
            //设置光标
            textView.selectedRange = selectRange

            
        }else{
            let str = (faceModel.code! as NSString).emoji()
            //把emoji表情插入光标后面的位置
            textView.insertText(str!)
        }
    }

    
    //MARK: - 键盘frame的监听通知方法
    func keyBoardChange(noti: NSNotification){
        let rect = noti.userInfo?[UIKeyboardFrameEndUserInfoKey] as! CGRect
        
        //        if rect.origin.y == ScreenHeight{
        //        toolBar.snp.updateConstraints { (make) in
        //            make.bottom.equalTo(self.view).offset(-rect.size.height)
        //        }
        //        }else{
        //            toolBar.snp.updateConstraints { (make) in
        //                make.bottom.equalTo(self.view)
        //            }
        //        }
        
        toolBar.snp.updateConstraints { (make) in
            make.bottom.equalTo(self.view).offset(rect.origin.y - ScreenHeight)
        }
        
        UIView.animate(withDuration: 0.4) {
            self.view.layoutIfNeeded()
        }
        
        
    }
    
    //MARK: - 导航栏设置
    func setupNavi() {
        let lable = UILabel(fontSize: 16, textColor: UIColor.black)
        
        if let name = TTUserAccountViewModel.shareViewModel.userAccountModel?.name {
            let text = "发微博\n" + name
            
            //转成复文本
            let attrbuteText: NSMutableAttributedString = NSMutableAttributedString(string: text)
            
            let range = (text as NSString).range(of: name)
            
            attrbuteText.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12),NSForegroundColorAttributeName: UIColor.orange], range: range)
            
            lable.attributedText = attrbuteText
        }else{
            lable.text = "发微博"
        }
        lable.textAlignment = .center
        lable.numberOfLines = 0
        //不设置大小就不显示
        lable.sizeToFit()
        navigationItem.titleView = lable
        
        let leftItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancel))
        navigationItem.leftBarButtonItem = leftItem
        
        //直接设置item属性无效....
//        let rightItem = UIBarButtonItem(title: "发送", target: self, action: #selector(send))
//        navigationItem.rightBarButtonItem = rightItem
//        
//        //详细设置发送item
//        rightItem.setBackgroundImage(UIImage(named: "common_button_orange")?.withRenderingMode(.alwaysOriginal), for: .normal, barMetrics: .default)
//        rightItem.setBackgroundImage(UIImage(named: "common_button_orange_highlighted")?.withRenderingMode(.alwaysOriginal), for: .highlighted, barMetrics: .default)
//        rightItem.setBackgroundImage(UIImage(named: "common_button_disable")?.withRenderingMode(.alwaysOriginal), for: .disabled, barMetrics: .default)
//        
//        rightItem.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 14)], for: .normal)
        
        let button = UIButton()
        //  添加点击事件
        button.addTarget(self, action: #selector(send), for: .touchUpInside)
        //  设置不同状态下按钮的图片
        button.setBackgroundImage(UIImage(named: "common_button_orange"), for: .normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), for: .highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_disable"), for: .disabled)
        //  设置文字
        button.setTitle("发送", for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        button.setTitleColor(UIColor.white, for: .normal)
        button.setTitleColor(UIColor.gray, for: .disabled)
        //  设置大小
        button.frame.size = CGSize(width: 45, height: 35)
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
        
        //期初没有文字,禁用
        navigationItem.rightBarButtonItem?.isEnabled = false

        
    }
    
    
    //MARK: - 取消item和发送item的监听方法
    func send(){
        
        if picChooseView.picArray.count == 0{
            TTNetWorkTool.shareTool.requestSendWordWeiBo(linPai: (TTUserAccountViewModel.shareViewModel.userAccountModel?.access_token)!, status: textView.text, backClosure: { (response, error) in
                if error != nil{
                    print("发送失败")
                    return
                }
                print("发送成功")
            })
        }else{
            TTNetWorkTool.shareTool.requestSendWordAndImageWeiBo(source: appKey, status: textView.text, pic: picChooseView.picArray.first!, backClosure: { (response, error) in
                if error != nil{
                    print("发送失败")
                    return
                }
                print("发送成功")
            })
        }
    }
    func cancel(){
        
        self.dismiss(animated: true, completion: nil)
    }
    
    //MARK: - textView代理监听方法
    func textViewDidChange(_ textView: UITextView) {
        
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }

    
    //MARK: - 界面设置
    func setupUI(){
        
        //textView
        view.addSubview(textView)
        textView.backgroundColor = UIColor.cyan
        textView.delegate = self
        
        textView.becomeFirstResponder()

//        textView.bounces = true
        
        //colView
        textView.addSubview(picChooseView)
        
        //toolBar
        view.addSubview(toolBar)
        
        textView.snp.makeConstraints { (make) in
            make.top.equalTo(view).offset(100)
            make.centerX.equalTo(view)
            make.width.equalTo(view).offset(-10)
            make.height.equalTo(600)
//            make.bottom.equalTo(picChooseView).offset(20)
        }
        
//       self.view.layoutIfNeeded()
       
        picChooseView.snp.makeConstraints { (make) in
            make.top.equalTo(textView).offset(150)
//            make.bottom.equalTo(textView.snp.bottom).offset(20)
            make.centerX.equalTo(textView)
            make.width.equalTo(textView).offset(-10)
            make.height.equalTo(textView.snp.width).offset(-10)
        }
        
        picChooseView.clickAddPictureClusure = {[unowned self] in
            self.clickPictureButton()
        }
        
        
        
        toolBar.snp.makeConstraints { (make) in
            make.leading.trailing.bottom.equalTo(self.view)
            make.height.equalTo(40)
        }
        
        //toolBar闭包赋值
        toolBar.buttonClickClusure = {[unowned self] (type)->() in
            
            switch type {
            case .pictore:
                print("图片")
                self.clickPictureButton()
            case .smileface:
                print("笑脸")
                self.clickSmilefaceButton()
            case .keyboard:
                print("键盘")
            case .add:
                print("加号")
            case .mention:
                print("@")
            }
        }
    }
    
    //MARK: - 点击表情按钮跳转表情界面
    func clickSmilefaceButton(){
        
        //第一次点击,如果是nil,就变成表情视图,并且按钮图片变为键盘
        if textView.inputView == nil{
            //设置inputView属性可以改变弹出视图
            textView.inputView = faceChoose

            toolBar.swithPictureFaceAndKeyBoard(isFace: true)
        }else{
            textView.inputView = nil
            toolBar.swithPictureFaceAndKeyBoard(isFace: false)
        }

        
        //要使inputView生效,就要成为第一响应者和重新加载输入视图
        textView.becomeFirstResponder()
        textView.reloadInputViews()
        
    }
    
    deinit {
        //销毁通知中心
        NotificationCenter.default.removeObserver(self)
    }

}


//MARK: - 使用相机,并遵守代理
extension SendViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    //MARK: - 点击相机按钮实现相机实例化
    func clickPictureButton() {
        
        let pickerController = UIImagePickerController()
        
        pickerController.delegate = self
        
        //判断手机是否支持相机
        if UIImagePickerController.isSourceTypeAvailable(.camera){
            
            pickerController.sourceType = .camera
        }else{
            pickerController.sourceType = .photoLibrary
        }
        //弹出控制器
        self.present(pickerController, animated: true, completion: nil)
    
    }
    
    //MARK: - 选择图片调用的代理方法
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        //压缩图片
        let newImage = scaleImage(scaleMultiple: 0.5, image: image)
        
        picChooseView.addImageToArray(image: newImage)
        
        picker.dismiss(animated: true, completion: nil)
    }
    
    //MARK: - 压缩图片
    func scaleImage(scaleMultiple: CGFloat, image: UIImage) -> UIImage {
        
        //压缩后的大小
        let scaleSize = CGSize(width: image.size.width * scaleMultiple, height: image.size.height * scaleMultiple)
        
        //开启图片上下文
        UIGraphicsBeginImageContext(scaleSize)
        //渲染区域
        let rect = CGRect(origin: CGPoint.zero, size: scaleSize)
        //把图片渲染到指定位置
        image.draw(in: rect)
        //通过图形上下文获取这个图片
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        //结束图形上下文
        UIGraphicsEndImageContext()
        
        return newImage!
    }
    
    
    
    
    
}
